import axios from 'axios'
import { Toast } from 'antd-mobile'
import { getTokenInfo, setTokenInfo } from './storage'
import history from '@/utils/history'
import store from '@/store'
import { logout, saveToken } from '@/store/actions/login'
const baseURL = 'http://geek.itheima.net/v1_0/'
const request = axios.create({
  timeout: 5000,
  baseURL,
})

request.interceptors.request.use(
  (config) => {
    const token = getTokenInfo().token
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (error.response && error.response.data && error.response.data.message) {
      //token是否过期
      if (error.response.status !== 401) {
        Toast.info(error.response.data.message, 1)
      } else {
        const { refresh_token } = getTokenInfo()
        //是否有refresh_token
        if (!refresh_token) {
          history.push({
            pathname: '/login',
            state: {
              from: history.location.pathname,
            },
          })
        } else {
          try {
            const res = await axios({
              url: baseURL + 'authorizations',
              method: 'PUT',
              headers: {
                Authorization: 'Bearer ' + refresh_token,
              },
            })
            const tokenInfo = {
              token: res.data.data.token,
              refresh_token: refresh_token,
            }
            // 保存到redux中
            store.dispatch(saveToken(tokenInfo))
            // 保存到localstorage中
            setTokenInfo(tokenInfo)
            // token刷新成功后，重新把最开始失败的请求重新发一次
            return request(error.config)
          } catch {
            //refresh_token过期
            store.dispatch(logout())
            history.push({
              pathname: '/login',
              state: {
                from: history.location.pathname,
              },
            })
            Toast.info('登录信息失效，请重新登录')
          }
        }
      }
    } else {
      Toast.info('网络繁忙,请稍后重试', 1)
    }
    return Promise.reject(error)
  }
)

export default request
